﻿--[[
计算 userdata 容器的算术平均值

参数:
    container (userdata): 包含数值数据的 NLua 容器对象

返回:
    number: 容器元素的平均值

抛出:
    当容器为空或包含非数值元素时抛出错误

示例:
    -- C# 端传入：new List<float> {1.5, 2.5, 3.5}
    Mean(data)  -- 返回 2.5
]]
function Mean_Lua(container)
    -- 复用类型检查
    if type(container) ~= "userdata" then
        error(string.format(
            "bad argument #1 to 'Mean' (userdata expected, got %s)",
            type(container)
        ), 2)
    end

    local sum = 0
    local count = 0

    for i = 0, container.Length - 1 do
        value = container[i]
        if type(value) ~= "number" then
            error("container contains non-numeric elements", 2)
        end

        sum = sum + value
        count = count + 1
    end

    if count == 0 then
        error("cannot calculate mean of empty container", 2)
    end

    return sum / count
end